package com.cooper.scraper.show;

import java.util.ArrayList;
import java.util.List;

import com.cooper.scraper.R;
import com.cooper.scraper.ResourceScraper;
import com.cooper.scraper.ResourceScraperRunner;
import com.cooper.scraper.RunnerSubscribe;
import com.cooper.scraper.ScraperBrowseParam;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class BrowseParamPopMenu implements
		android.widget.AdapterView.OnItemClickListener, RunnerSubscribe {

	public interface OnParamSelectListener {
		public void onParamSelect(List<ScraperBrowseParam> param);
	}

	// private ArrayList<String> itemList;
	private Context context;
	private PopupWindow popupWindow;
	// private ScraperBrowseParam orderParam = null;
	private OnParamSelectListener listener;
	private LayoutInflater inflater;
	private ResourceScraperRunner<?> runner;
	private String scraperId;
	private View mainView;

	// private PopAdapter listAdapter;

	public BrowseParamPopMenu(Context context, ResourceScraperRunner<?> runner,
			String scraperId) {
		super();
		this.context = context;
		this.runner = runner;
		this.scraperId = scraperId;

		runner.subscribe(this);
		runner.getBrowseParams(context, scraperId);

		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mainView = inflater.inflate(R.layout.popmenu, null);

		mainView.findViewById(R.id.downaloadFailView).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						BrowseParamPopMenu.this.runner
								.subscribe(BrowseParamPopMenu.this);
						BrowseParamPopMenu.this.runner.getBrowseParams(
								BrowseParamPopMenu.this.context,
								BrowseParamPopMenu.this.scraperId);

						mainView.findViewById(R.id.progressBarLayout)
								.setVisibility(View.VISIBLE);
						mainView.findViewById(R.id.downaloadFailView)
								.setVisibility(View.GONE);
					}
				});

		popupWindow = new PopupWindow(mainView, context.getResources()
				.getDimensionPixelSize(R.dimen.popmenu_width),
				LayoutParams.WRAP_CONTENT);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景（很神奇的）
		popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		if (listener != null) {
			List<ScraperBrowseParam> result = new ArrayList<ScraperBrowseParam>(
					1);
			result.add((ScraperBrowseParam) parent.getItemAtPosition(position));
			listener.onParamSelect(result);
		}
		dismiss();
	}

	public void setOnParamSelectListener(OnParamSelectListener listener) {
		this.listener = listener;
	}

	public void showAsDropDown(View parent) {
		popupWindow.showAsDropDown(parent, context.getResources()
				.getDimensionPixelSize(R.dimen.popmenu_xoff), context
				.getResources().getDimensionPixelSize(R.dimen.popmenu_yoff));

		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.update();
	}

	public void dismiss() {
		popupWindow.dismiss();
	}

	private final class PopAdapter extends BaseAdapter {

		private List<String> items;
		private ScraperBrowseParam orderParam;

		public PopAdapter(ScraperBrowseParam orderParam) {
			super();
			this.orderParam = orderParam;
			items = new ArrayList<String>(orderParam.getParamList().keySet());
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			orderParam.setKey(items.get(position));
			return orderParam;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.pomenu_item, null);
				holder = new ViewHolder();
				convertView.setTag(holder);
				holder.groupItem = (TextView) convertView
						.findViewById(R.id.textView);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			String key = items.get(position);

			holder.groupItem.setText(orderParam.getParamList().get(key));
			if (orderParam.getKey().equals(key)) {
				holder.groupItem.setTextColor(context.getResources()
						.getColorStateList(
								R.drawable.item_pop_select_text_color));
			} else {
				holder.groupItem.setTextColor(context.getResources()
						.getColorStateList(R.drawable.item_pop_text_color));
			}

			return convertView;
		}

		private final class ViewHolder {
			TextView groupItem;
		}
	}

	@Override
	public void onDownloadComplete(String key, Object data) {

		@SuppressWarnings("unchecked")
		List<ScraperBrowseParam> params = (List<ScraperBrowseParam>) data;

		ScraperBrowseParam orderParam = null;
		for (ScraperBrowseParam param : params) {
			if (param.getType() == ScraperBrowseParam.ORDER_PARAM) {
				orderParam = param;
				break;
			}
		}

		if (orderParam == null) {
			mainView.findViewById(R.id.progressBarLayout).setVisibility(
					View.GONE);
			mainView.findViewById(R.id.downaloadFailView).setVisibility(
					View.VISIBLE);
		} else {

			mainView.findViewById(R.id.progressBarLayout).setVisibility(
					View.GONE);
			mainView.findViewById(R.id.downaloadFailView).setVisibility(
					View.GONE);

			ListView listView = (ListView) mainView.findViewById(R.id.listView);

			listView.setAdapter(new PopAdapter(orderParam));
			listView.setOnItemClickListener(this);
			listView.setVisibility(View.VISIBLE);

		}
		runner.cancelSubscribe(this, false);
	}

	@Override
	public void onDownloadFail(String key, int errorCode) {
		mainView.findViewById(R.id.progressBarLayout).setVisibility(View.GONE);
		mainView.findViewById(R.id.downaloadFailView).setVisibility(
				View.VISIBLE);
		runner.cancelSubscribe(this, false);
	}

	@Override
	public void onDownloadCancel(String key) {
	}

	@Override
	public boolean subscribed(String key) {
		return key.equals(ResourceScraper.BROWSE_URL_PARAM_SUBSCRIBE_PREFIX
				+ scraperId);
	}
}
